package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"https_golang/model"
	"https_golang/my_jwt"
)

func jwtModule(server *gin.Engine) {
	var jwtGroup = server.Group("/jwt")

	jwtGroup.GET("/secret", getJwtSecret)
	jwtGroup.GET("/secret/:secret", updateJwtSecret)
	jwtGroup.GET("/generate", generateJwtToken)
	jwtGroup.GET("/verify", verifyJwtToken)
}

func generateJwtToken(ctx *gin.Context) {
	generate, err := my_jwt.JWTHandler.Generate()
	if err == nil {
		ctx.JSON(200,
			model.NewResponse(200, "success", generate))
	} else {
		ctx.JSON(500,
			model.NewResponse(500, "failed", err.Error()))
	}
}

// 我们规定需要校验的jwt token 放在请求头(jwt)中
func verifyJwtToken(ctx *gin.Context) {
	// 获取请求头中的jwt token
	var jwtToken = ctx.Request.Header.Get("jwt")
	// 校验jwt token
	var _, err = my_jwt.JWTHandler.Verify(jwtToken)

	if err == nil {
		fmt.Println("parse success")
		ctx.JSON(200,
			model.NewResponse(200, "success", nil))
	} else {
		// 这里我们将jwt token 也返回给前端, 方便调试
		fmt.Println("parse failed")
		ctx.JSON(401,
			model.NewResponse(500, "failed to pass: "+jwtToken, err.Error()))
	}
}

func updateJwtSecret(ctx *gin.Context) {
	var secret = ctx.Param("secret")
	if secret == "" {
		ctx.JSON(400,
			model.NewResponse(400, "failed", "secret is empty"))
	} else {
		my_jwt.JWTHandler.UpdateSecret(secret)
		ctx.JSON(200,
			model.NewResponse(200, "success", nil))
	}
}

func getJwtSecret(ctx *gin.Context) {
	ctx.JSON(200,
		model.NewResponse(200, "success", my_jwt.JWTHandler.GetSecret()))
}
